package com.tencent.wepay.handler.validation;

import java.lang.reflect.Field;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tencent.wepay.annotation.NotBlank;
import com.tencent.wepay.handler.ValidationHandler;
import com.tencent.wepay.protocol.domain.Validation;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
public class NotBlankHandler implements ValidationHandler{
	private final static Logger logger=LoggerFactory.getLogger(NotBlankHandler.class);
	@Override
	public boolean handler(Validation v,Field field) {
		@SuppressWarnings("rawtypes")
		Class clz=v.getClass();
		String fieldName=field.getName();
		NotBlank notBlank=(NotBlank) field.getAnnotation(NotBlank.class);
		try {
			Object value=field.get(v);
			String relate=notBlank.relate();
			String[] values=notBlank.value();
			if(StringUtils.isNotBlank(relate)){
				try {
					Field relateField=clz.getDeclaredField(relate);
					relateField.setAccessible(true);
					Object relateValue=relateField.get(v);
					for (String vl : values) {
						if(StringUtils.isBlank(vl)){
							continue;
						}
						if((relateValue!=null&&vl.equalsIgnoreCase(relateValue.toString())&&(value==null||StringUtils.isBlank( value.toString())))||(StringUtils.isBlank(vl)&&(value==null||StringUtils.isBlank(value.toString()))&&(relateValue==null||StringUtils.isBlank(relateValue.toString())))){
							logger.error("["+fieldName+"]"+notBlank.desc());
							return false;
						}
					}
				} catch (NoSuchFieldException | SecurityException e) {
					logger.error("["+fieldName+"] the field relateField is not exist");
					return false;
				}
			}
			else if(value==null||StringUtils.isBlank((String) value)){
				logger.error("["+fieldName+"]"+notBlank.desc());
				return false;
			}
		}catch (IllegalArgumentException | IllegalAccessException e) {
			return false;
		}
		return true;
	}

	@Override
	public boolean access(Field field) {
		return field.getType().equals(String.class);
	}
	
}
